// pages/conference/conference.js
import meetingRoom from '../../config/api/meetingRoom' // 引入api接口管理文件
const dayjs = require("./dayjs");
var WxNotificationCenter = require("../../config/WxNotificationCenter");
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //底部安全区高度
    bottomLift: app.globalData.bottomLift,
    scrollHeight: 0,
    // 会议室集合
    conferenceList: [{
      name: "加载中"
    }],
    conferenceitem: {
      name: "加载中"
    },
    huiyishow: false,
    // 会议室选中
    conferenceIndex: 0,
    openid: '',
    // 日期集合
    dateList: [],
    // 日期选中
    dateIndex: 0,
    timeIndex: 0,
    // 列表
    appointmentList: [],
    initmentlist: [{
        time: '08:00-09:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '09:00-10:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '10:00-11:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '11:00-12:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '12:00-13:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '13:00-14:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '14:00-15:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '15:00-16:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '16:00-17:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '17:00-18:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '18:00-19:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '19:00-20:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '20:00-21:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
      {
        time: '21:00-22:00',
        status: 0,
        name: '空闲中',
        timeout: false,
      },
    ]
  },

  // 选中日期
  chooseDate(e) {
    let cindex = e.currentTarget.dataset.index;
    if (cindex == this.data.dateIndex) {
      return;
    }
    this.setData({
      dateIndex: cindex,
      timeIndex: 0,
    })
    this.getRecord();
  },
  // 选中时间
  chooseTime(e) {
    let cindex = e.currentTarget.dataset.index;
    if (cindex == this.data.timeIndex) {
      return;
    }
    this.setData({
      timeIndex: cindex,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.list) {
      let list = JSON.parse(options.list);
      let index = options.selectindex;
      this.setData({
        conferenceList: list,
        conferenceitem: list[index],
        conferenceIndex: index
      })

    } else {
      this.loadData();
    }

    this.setData({
      openid: app.globalData.openid,
    })


    //处理时间往后七天
    let maplist = []
    for (let index = 0; index < 7; index++) {
      let date = dayjs().add(index, 'day');
      let w = this.weektostring(dayjs(date).format("d"));
      let map = {
        "date": date,
        "format": dayjs(date).format("MM月DD日"),
        "week": w,
      }
      maplist.push(map);
    }
    //处理时间数据appointmentList
    let mentlist = this.data.initmentlist;
    mentlist = mentlist.map(res => {
      let times = res.time.split('-');
      res.stime = times[0];
      res.etime = times[1];
      return res;
    })


    this.setData({
      dateList: maplist,
      initmentlist: mentlist
    })

    var that = this
    WxNotificationCenter.addNotification('getRecord', that.getRecord, that)


    if (options.list) {
      this.getRecord();
    }
  },
  weektostring(index) {
    index = index * 1;
    switch (index) {
      case 0:
        return "周日";
      case 1:
        return "周一";
      case 2:
        return "周二";
      case 3:
        return "周三";
      case 4:
        return "周四";
      case 5:
        return "周五";
      case 6:
        return "周六";
      default:
        return "";
    }
  },
  loadData() {
    let vm = this;
    //加载会议室列表
    meetingRoom.list({
      "pageNo": 1,
      "pageSize": 9999
    }, function (res) {
      let list = res.data.data.records;
      vm.setData({
        conferenceList: list,
        conferenceitem: list[0]
      })
      vm.getRecord();
    })
  },
  //获取会议室预约记录
  getRecord() {
    let vm = this;
    let stime = dayjs(vm.data.dateList[vm.data.dateIndex].date).format("YYYY-MM-DD 00:00:00");
    let etime = dayjs(vm.data.dateList[vm.data.dateIndex].date).format("YYYY-MM-DD 23:59:59");
    meetingRoom.getMeetingRoomReservationRecord({
      "startTime": stime,
      "endTime": etime,
      "id": this.data.conferenceitem.id,
    }, function (res) {

      //处理预约数据
      let meetingReservations = res.data.data[0].meetingReservations;
      let mentlist = vm.data.appointmentList;
      let cdate = vm.data.dateList[vm.data.dateIndex].date;
    
      let date = dayjs(cdate).format("YYYY-MM-DD");
      let nowtime = new Date();
      for (let index = 0; index < mentlist.length; index++) {
        const item = mentlist[index];
        item.status = 0;
        item.name = '空闲中';
        for (let j = 0; j < meetingReservations.length; j++) {
          const item1 = meetingReservations[j];
          let startTime = item1.startTime;
          if (startTime == date + " " + item.stime + ":00") {
            item.status = 1;
            item.openId = item1.openId;
            item.hyid = item1.id;
            item.name = item1.name;
          }
        }
        //判断是否超时
        let lasttime = new Date(date + " " + item.etime + ":00");
        item.timeout = lasttime < nowtime;


      }
      vm.setData({
        appointmentList: mentlist
      })
    });
  },
  // 弹窗
  clickshowhy() {
    this.setData({
      huiyishow: true
    })
  },
  //点击预约
  clickyuyue() {
    let item = this.data.appointmentList[this.data.timeIndex];

    if (item.status == 1) {
      wx.showToast({
        title: '会议室已占用!',
        icon: 'none'
      })
      return;
    }
    if (item.timeout) {
      wx.showToast({
        title: '当前时间已过~',
        icon: 'none'
      })
      return;
    }


    item.ferenceitem = this.data.conferenceitem;
    let time = dayjs(this.data.dateList[this.data.dateIndex].date).format("YYYY-MM-DD");
    item.date = time;
    wx.navigateTo({
      url: '/pages/conferenceAdd/conferenceAdd?item=' + JSON.stringify(item),
    })

  },
  //取消预约
  clickquxiao(e) {
    let item = e.currentTarget.dataset.item;
    let content = `确定要取消${item.time}的预约么?`
    let vm = this;
    wx.showModal({
      title: '提示',
      content: content,
      success(res) {
        if (res.confirm) {
          //开始取消
          wx.showLoading({
            title: '取消中...',
          })
          meetingRoom.del({
            "id": item.hyid
          }, function (res) {
            wx.hideLoading({
              success: (res) => {},
            })
            if (res.data.status == 200) {
              wx.showToast({
                title: '取消成功',
                icon: "none"
              })
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: "none"
              })
            }
            vm.getRecord();
          })
        } else if (res.cancel) {

        }
      }
    })
  },
  onCloseshowhy() {
    this.setData({
      huiyishow: false
    })
  },
  //选中会议室
  onCinfirm(res) {
    let detail = res.detail
    this.setData({
      huiyishow: false,
      conferenceIndex: detail.index,
      conferenceitem: detail.value
    })
    this.getRecord();
  },
  onCancel() {
    this.setData({
      huiyishow: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getScrollHeight();

  },

  getScrollHeight() {
    //如果不加定时器，获取的元素的高度还是没渲染完异步数据前的高度
    let query = wx.createSelectorQuery();
    query.select('.leftDate').boundingClientRect(rect => {
      let height = rect.height; //单位：px
      console.log("rect", rect, height);
      this.setData({
        scrollHeight: height,
        appointmentList: this.data.initmentlist,
      })
    }).exec();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    var that = this
    WxNotificationCenter.removeNotification('getRecord', that)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})